package com.sz.mgc.goldrush;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.smile.okhttpintegration.OkCallback;
import com.smile.okhttpintegration.OkHttp;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

/*
@author 程序
* */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public class MainActivity extends AppCompatActivity implements View.OnKeyListener {
    //private String url = "http://moigem.cn:8080/";
    /**
     * 保存地址
     */
    private final String APK_SAVE_PATH = Environment.getExternalStorageDirectory() + "/MNUpdateAPK";
    private WebView mWebView;
    //  private String mUpdateUrl = "http://moigem.cn:8080/response.json";
    //private String mUpdateUrl = "https://raw.githubusercontent.com/WVector/AppUpdateDemo/master/json/json.txt";

    private int mCurrentVersionCode;
    private String[] permission = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.READ_EXTERNAL_STORAGE
            , Manifest.permission.READ_PHONE_STATE
    };
    private VersionBean mVersionBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = findViewById(R.id.gold_rush_web_view);
        statusBar();
        //权限
        permission();
        //获取版本
        getVersion();

        setWebView();
    }

    private void statusBar() {

    }

    private void permission() {
        Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(permission).build(), new AcpListener() {
            @Override
            public void onGranted() {
                Log.e("TAG", "权限同意");
            }

            @Override
            public void onDenied(List<String> permissions) {
                Log.e("TAG", "权限拒绝");
            }
        });
    }

    private void getVersion() {

        try {
            mCurrentVersionCode = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        getNetVersion();
    }

    private void getNetVersion() {
        HashMap<String, Object> map = new HashMap<>();

        //获取最新版本url
        String versionUrl = "http://moigem.cn:8080/response.json";
        OkHttp.post(versionUrl, map, new OkCallback() {
            @Override
            public void onResponse(String response) {
                Log.e("getNetVersion=", response);
                Type type = new TypeToken<VersionBean>() {
                }.getType();
                Gson gson = new Gson();
                mVersionBean = gson.fromJson(response, type);
                Log.e("versionBean=", mVersionBean.getId()+"");
                if (mVersionBean.getId() > mCurrentVersionCode) {
                    Log.e("需要更新", "需要更新");
                    initVersion();//下载
                } else {
                    Log.e("不需要更新", "不需要更新");
                }
            }

            @Override
            public void onFailure(String error) {
                Log.e("error=", error);
            }
        });
    }

    private void initVersion() {
        //下载链接
       // String mUpdateUrl = "https://raw.githubusercontent.com/WVector/AppUpdateDemo/master/json/json.txt";
        String mUpdateUrl = "http://moigem.cn:8080/response.json";
        //最简方式
        new UpdateAppManager
                .Builder()
                .setActivity(this)
                //更新地址
                .setUpdateUrl(mUpdateUrl)
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .build()
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            updateAppBean
                                    //（必须）是否更新Yes,No
                                    .setUpdate("Yes")
                                    //（必须）新版本号，
                                    .setNewVersion("1.1.0")
                                    //（必须）下载地址
                                    .setApkFileUrl(mVersionBean.getUrl())
                                    //（必须）更新内容
                                    .setUpdateLog("• 支持文字、贴纸、背景音乐，尽情展现欢乐气氛；\n• 两人视频通话支持实时滤镜，丰富滤镜，多彩心情；\n• 图片编辑新增艺术滤镜，一键打造文艺画风；\n• 资料卡新增点赞排行榜，看好友里谁是魅力之王。")

                                    //大小，不设置不显示大小，可以不设置
                                    .setTargetSize("2M")
                                    //是否强制更新，可以不设置
                                    .setConstraint(true);
                                    //设置md5，可以不设置
                                //    .setNewMd5(jsonObject.optString("new_md51"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return updateAppBean;
                    }

                    @Override
                    protected void noNewApp(String error) {
                        Log.e("更新=", error);
                    }
                });
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void setWebView() {
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);


        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                mWebView.loadUrl(url);
                return true;
            }
        });

        //webView内容链接
        String url = "http://moigem.cn:8080/";
        mWebView.loadUrl(url);
    }

   /* @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            }
        }
        return false;
    }*/
   //返回,不会直接退出

   @Override
   public boolean onKey(View v, int keyCode, KeyEvent event) {
       if (event.getAction() == KeyEvent.ACTION_DOWN) {
           if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
               mWebView.goBack();
               return true;
           }
       }
       return false;

   }
}
